#include<brpc/channel.h>
#include<thread>
#include"main.pb.h"
void callback(brpc::Controller* controller,
                       ::example::EchoResponse* response)
{
    std::unique_ptr<brpc::Controller> cntl_guard(controller);
    std::unique_ptr<::example::EchoResponse> resp_guard(response);
    if(cntl_guard->Failed()==true)
    {
        std::cout<<"RPC调用失败"<<cntl_guard->ErrorText()<<std::endl;
        return;
    }
    std::cout<<"收到回复:"<<resp_guard->message()<<std::endl;
}



int main()
{
    //1.构建channel信道对象
    brpc::Channel channel;
        //测试一下对channel进行配置
        brpc::ChannelOptions options;
        options.connect_timeout_ms = -1;//配置连接等待超时时间
        options.timeout_ms = -1;//配置rpc请求等待时间
        options.max_retry = 3;//请求重试次数
        options.protocol = "baidu_std";//序列化协议，默认使用baidu_std
    //2.对channel进行初始化，即连接服务器
    int ret = channel.Init("127.0.0.1:8080",&options);
    if(ret==-1)
    {
        std::cout<<"初始化channel失败\n";
        return -1;
    }
    //3.构建EchoService_Stub对象，用于RPC调用
    ::example::EchoService_Stub stub(&channel);
    //4.进行RPC调用
    ::example::EchoRequest req;
    req.set_message("你好 zzy");
    //因为如果需要用到异步调用的时候，异步调用可能会直接对cntl和rep进行释放，所以不能简单定义到栈上
    brpc::Controller* cntl = new brpc::Controller();
    ::example::EchoResponse* resp = new ::example::EchoResponse();
    //stub.Echo(cntl,&req,resp,nullptr);//同步调用
    auto closure = google::protobuf::NewCallback(callback,cntl,resp);
    stub.Echo(cntl,&req,resp,closure);
    std::cout<<"异步调用结束\n";
    std::this_thread::sleep_for(std::chrono::seconds(3));
    return 0;
}